package com.cnhis.cloudhealth.clidoctorweb.gzip;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

import org.apache.commons.io.FileUtils;

public class GzipUtil {
	
	public static void main(String[] args) throws UnsupportedEncodingException {
		
		String  s="测试数据测试数据测试数据测试数据测试数据";
		byte[] buff=s.getBytes("gbk");
		System.out.println(buff.length);
		
		byte[] buff_ziped = gzip(buff);
		
		
		System.out.println(buff_ziped.length);
		
		System.out.println("unzip:"+ new String( uncompress(buff_ziped) ,"gbk"));
	}

	
	public static byte[] uncompress(byte[] bytes) {  
        if (bytes == null || bytes.length == 0) {  
            return null;  
        }  
        ByteArrayOutputStream out = new ByteArrayOutputStream();  
        ByteArrayInputStream in = new ByteArrayInputStream(bytes);  
        try {  
            GZIPInputStream ungzip = new GZIPInputStream(in);  
            byte[] buffer = new byte[256];  
            int n;  
            while ((n = ungzip.read(buffer)) >= 0) {  
                out.write(buffer, 0, n);  
            }  
        } catch (IOException e) {  
        	throw new RuntimeException(e);
        }  
  
        return out.toByteArray();  
    }  
	
	
	public static byte[] gzip(byte[] buff) {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();

		GZIPOutputStream gzip = null;
		try {
			gzip = new GZIPOutputStream(baos);
		} catch (IOException e1) {
			throw new RuntimeException(e1);
		}

		try {
			gzip.write(buff);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}

		try {
			gzip.close();
		} catch (IOException e) {
			throw new RuntimeException(e);
		}

		byte[] buff_ziped = baos.toByteArray();
		return buff_ziped;
	}


	private byte[] bytearr;
	private byte[] bytearr_ziped;


	public   GzipUtil gzip(String f) {
		try {
		
			this.bytearr = FileUtils.readFileToByteArray(new File(f) );
			this.bytearr_ziped=gzip(this.bytearr);
			
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
		return this;
	}


	public static GzipUtil newx() {
		// TODO Auto-generated method stub
		return new GzipUtil();
	}


	public void toFile(String f) {
		try {
			FileUtils.writeByteArrayToFile(new File(f), this.bytearr_ziped);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
		
	}

}
